package com.jrx.anytxn.accounting.job.mergeFile.step;

import com.jrx.anytxn.accounting.bean.DealBillBean;
import com.jrx.anytxn.accounting.config.PathConfig;
import com.jrx.anytxn.accounting.entity.GaVoucherInfo;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

/**
 * @author xqy
 * @version 1.0
 * @date 2019/11/27
 */
public class MergeFileListener implements JobExecutionListener {
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private PathConfig pathConfig;

    private Map<String, GaVoucherInfo> mergeMap;

    public MergeFileListener(Map<String, GaVoucherInfo> mergeMap){
        this.mergeMap = mergeMap;
    }

    @Override
    public void beforeJob(JobExecution jobExecution) {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        String today = DateUtils.format(org.getToday(), "yyyyMMdd");
        String mergePath = pathConfig.getBasePath() + "/mergeFile/" + org.getTenantId() + "/" + "mergeFileBatch_" + pathConfig.getBatchTaskId() + "_" + today + ".txt";
        //根据文件路径删除文件
        deleteFile(mergePath);
        mergeMap.clear();
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        mergeMap.clear();
    }

    /**
     * 删除文件
     * @param path
     */
    private static void deleteFile(String path) {
        Path fpath = Paths.get(path);
        //文件存在，删除文件
        if (fpath.toFile().exists()) {
            try {
                Files.delete(fpath);
            } catch (IOException e) {
                //因为listener实现的原接口未对异常做处理，所以不能抛出普通异常。
                throw new RuntimeException(e);
            }
        }
    }
}